package com.nopay.cdxphone.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.nopay.cdxphone.utils.CallLogHelper;

public class PhoneBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            // TODO 拨打电话
//            String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//            Log.e("PhoneBroadcastReceiver", "正在拨打：" + phoneNumber);
        } else {
            // TODO 接听电话
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            Log.e("PhoneBroadcastReceiver", tManager.getCallState() + "");
            if(tManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
                if(PhoneBroadcastReceiver.onCallFinishListener == null) return;

                PhoneBroadcastReceiver.onCallFinishListener.onCallFinish(0, null);
                CallLogHelper.CallLogItem callLogItem = getCallLog(context,5);
                if(PhoneBroadcastReceiver.onCallFinishListener != null) PhoneBroadcastReceiver.onCallFinishListener.onCallFinish(1, callLogItem);
                PhoneBroadcastReceiver.onCallFinishListener = null;
            }
//            switch (tManager.getCallState()) {
//                case TelephonyManager.CALL_STATE_RINGING:
//                    Log.e("PhoneBroadcastReceiver", "接听电话状态：来电" + intent.getStringExtra("incoming_number"));
//                    break;
//                case TelephonyManager.CALL_STATE_OFFHOOK:
//                    Log.e("PhoneBroadcastReceiver", "接听电话状态：摘机");
//                    break;
//                case TelephonyManager.CALL_STATE_IDLE:
//                    Log.e("PhoneBroadcastReceiver", "接听电话状态：挂断");
//                    break;
//            }
        }
    }

    private CallLogHelper.CallLogItem getCallLog(Context context, int times) {
        CallLogHelper.CallLogItem callLogItem = CallLogHelper.fetchNewCallLog(context);
        if(callLogItem == null) {
            if(times > 0) {
                times--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCallLog(context, times);
            }
        }
        return callLogItem;
    }

    private static OnCallFinishListener onCallFinishListener;

    public static void setOnCallFinishListener(OnCallFinishListener onCallFinishListener) {
        PhoneBroadcastReceiver.onCallFinishListener = onCallFinishListener;
    }

    public interface OnCallFinishListener {

        void onCallFinish(int status, CallLogHelper.CallLogItem callLogItem);
    }
}
